package org.example.service.handleJudgeResultImpl;

import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j;
import org.example.pojo.Request.UserRuncodeCase;
import org.example.pojo.Response.JudgeResponse;
import org.example.pojo.Response.JudgeResult;
import org.example.pojo.Result;
import org.example.pojo.ResultCode;
import org.example.pojo.Submissions;
import org.example.service.handleJudgeResult;
import org.example.socket.WebSocket;
import org.example.socket.WebSocketRunCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;

@Component("handleJudgeResult")
@Log4j
public class handleJudgeResultImpl implements handleJudgeResult {

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private WebSocketRunCode webSocketRunCode;

    @Autowired
    private AsyncSaveJudge asyncSaveJudge;

    @Override
    @Transactional
    @Async("AsyncGetJudge")
    public void result(Submissions submissions, List<JudgeResult> list) {
        //判断是否为空
        if(list.isEmpty()){
            webSocket.sendOneMessage(submissions.getUserId(),JSONUtil.toJsonStr(
                    Result.builder().code(ResultCode.ERROR_SUBMIT.getCode())
                            .desc(ResultCode.ERROR_SUBMIT.getMsg())
                            .build()));
            return;
        }
        //定义数据分析结果、
        JudgeResponse judgeResponse=new JudgeResponse();

        //对判题数据处理
        //1.判定所有样例是否通过
        long count = list.stream().filter(f -> f.getStatus().getId() != 3).count();

        System.out.println(list.get(0).getStatus().getId());
        if(count>0){
            //失败状态码
            judgeResponse.setStatus_code(0);
            //设置编译输出
            if(Objects.isNull(list.get(0).getStderr())){
                judgeResponse.setCompare_result(list.get(0).getStatus().getDescription());
            }else {
                judgeResponse.setCompare_result(list.get(0).getStderr());
            }

            judgeResponse.setRun_success(false);
        }else {
            judgeResponse.setRun_success(true);
            //设置运行时间
            Double average = list.stream()
                    .mapToDouble(m -> Double.parseDouble(m.getTime()))
                    .average().getAsDouble();

            judgeResponse.setStatus_runtime(average);
            //设置运行内存
            double memoryDouble = list.stream().mapToDouble(JudgeResult::getMemory).average().getAsDouble();
            judgeResponse.setMemory(memoryDouble);
            //设置编译输出
            judgeResponse.setCompare_result(list.get(0).getCompile_output());

            judgeResponse.setStatus_code(1);
        }
        //设置问题ID
        judgeResponse.setQuestion_id(submissions.getProblemId());
        //返回前端
        judgeResponse.setFinished(true);

        webSocket.sendOneMessage(submissions.getUserId(), JSONUtil.toJsonStr(Result.builder().code(ResultCode.SUCCESS_GET_RESULT.getCode()).data(judgeResponse).build()));

        //TODO 对结果数据保存
        asyncSaveJudge.save(submissions, list);

    }


    public void CaseResult(List<UserRuncodeCase> list){
        //判断是否为空
        if(list.isEmpty()){
          log.error("数据异常！");
            return;
        }
        webSocketRunCode.sendOneMessage(list.get(0).getUserId(),JSONUtil.
                toJsonStr(Result.builder().code(ResultCode.SUCCESS_CASE.getCode())
                        .data(list).build()));
        //TODO 优化


    }
}

